package com.lipl.base.javase.utils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.time.LocalTime;
import java.util.Map;
import java.util.concurrent.*;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

/**
 * http请求工具类
 */
public class OkHttpUtil {

	private static final Logger LOGGER = LoggerFactory.getLogger(OkHttpUtil.class);

	private final static int TIMEOUT_CONNECTION = 20;// 超时连接时间
	private final static int TIMEOUT_READ = 30; // 读超时
	private final static int TIMEOUT_WRITE = 10;// 写超时

	public static OkHttpClient okHttpClient;

	static {
		okHttpClient = new OkHttpClient.Builder()//
				.connectTimeout(TIMEOUT_CONNECTION, TimeUnit.SECONDS)//
				.readTimeout(TIMEOUT_READ, TimeUnit.SECONDS)//
				.writeTimeout(TIMEOUT_WRITE, TimeUnit.SECONDS)//
				.build();
	}

	// GET请求返回对象
	public static <T> T doGet(String url, Class<T> clz) {
		Request request = new Request.Builder().url(url).build();
		Call call = okHttpClient.newCall(request);
		try {
			Response response = call.execute();
			return parseResponseObject(response, clz);
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
		return null;
	}

	// GET请求返回MAP
	public static Map<String, Object> doGet(String url) {
		Request request = new Request.Builder().url(url).build();
		Call call = okHttpClient.newCall(request);
		try {
			Response response = call.execute();
			return parseResponse(response);
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
		return null;
	}

	// POST表单格式
	public static Map<String, Object> doPost(String url, Map<String, String> map) {
		// 构建一个formBody builder
		FormBody.Builder builder = new FormBody.Builder();
		if (map != null) {
			// 循环form表单，将表单内容添加到form builder中
			for (Map.Entry<String, String> entry : map.entrySet()) {
				String key = entry.getKey();
				String value = entry.getValue();
				LOGGER.info("key -- > " + key + " value -- > " + value);
				builder.add(key, value);
			}
		}
		// 构建formBody，将其传入Request请求中
		FormBody body = builder.build();
		Request request = new Request.Builder().url(url).post(body).build();
		Call call = okHttpClient.newCall(request);
		// 返回请求结果
		try {
			Response response = call.execute();
			return parseResponse(response);
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
		return null;
	}

	// POST JSON格式
	public static Map<String, Object> doPost(String url, String json) {
		RequestBody body = RequestBody.create(MediaType.parse("application/json;charset=utf-8"), json);
		Request request = new Request.Builder().post(body).url(url).build();
		Call call = okHttpClient.newCall(request);
		// 返回请求结果
		try {
			Response response = call.execute();
			return parseResponse(response);
		} catch (IOException e) {
			LOGGER.error(e.getMessage());
		}
		return null;
	}

	// JSON转MAP
	private static Map<String, Object> parseResponse(Response response) throws IOException {
		String s = response.body().string();
		@SuppressWarnings("unchecked")
		Map<String, Object> map = JSON.parseObject(s, Map.class);
		return map;
	}
	
	// JSON转对象
	private static <T> T parseResponseObject(Response response, Class<T> clz) {
		try {
			String s = response.body().string();
			return JSON.parseObject(s, clz);
		} catch (Exception e) {
			LOGGER.error(e.getMessage());
		}
		return null;
	}
	
	public static Map<String, Object> headerDoPost(String urls, String query) {
		String resp = null;
		// String query = obj.toString();
		try {
			URL url = new URL(urls); // url地址

			HttpURLConnection connection = (HttpURLConnection) url.openConnection();
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setRequestMethod("POST");
			connection.setUseCaches(false);
			connection.setInstanceFollowRedirects(true);
			connection.setRequestProperty("Content-Type", "application/json");
			connection.connect();

			try (OutputStream os = connection.getOutputStream()) {
				os.write(query.getBytes("UTF-8"));
			}

			try (BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()))) {
				String lines;
				StringBuffer sbf = new StringBuffer();
				while ((lines = reader.readLine()) != null) {
					lines = new String(lines.getBytes(), "utf-8");
					sbf.append(lines);
				}
				LOGGER.info("返回来的报文：" + sbf.toString());
				resp = sbf.toString();

			}
			connection.disconnect();

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			JSONObject json = (JSONObject) JSON.parse(resp);
		}
		return JSON.parseObject(resp, Map.class);
	}

    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newFixedThreadPool(500);
        CountDownLatch latch = new CountDownLatch(1000);
        System.out.println("start" + LocalTime.now());
        for(int i=0 ;i<1000 ;i++) {
            executor.execute(() -> {
                try {
                    String jsonStr = "{\n" +
                            "    \"cainfo\":\"1\",\n" +
                            "        \"dev_no\":\"11111\",\n" +
                            "        \"dev_safe_info\":\"213123\",\n" +
                            "        \"fixmedins_code\":\"H44150200055\",\n" +
                            "        \"fixmedins_name\":\"广东汕尾红海湾经济开发区东洲街道社区卫生服务中心\",\n" +
                            "        \"inf_time\":\"2020-09-29 01:54:51\",\n" +
                            "        \"infno\":\"5303\",\n" +
                            "        \"infver\":\"V1.0\",\n" +
                            "            \"input\": {\n" +
                            "      \"data\": {\n" +
                            "                \"begntime\":\"2020-09-29 01:54:51\",\n" +
                            "                \"endtime\":\"2020-10-29 01:54:51\",\n" +
                            "          \"psn_no\": \"1334250260\"\n" +
                            "        }\n" +
                            "    },\n" +
                            "    \"insuplc_admdvs\":\"441500\",\n" +
                            "        \"mdtrtarea_admvs\":\"441500\",\n" +
                            "        \"msgid\":\"H44150200055202009290154511234\",\n" +
                            "        \"opter\":\"111\",\n" +
                            "        \"opter_name\":\"测试1\",\n" +
                            "        \"opter_type\":\"1\",\n" +
                            "        \"recer_sys_code\":\"11\",\n" +
                            "        \"sign_no\":\"1\",\n" +
                            "        \"signtype\":\"SM2\"\n" +
                            "}\n";
                    JSONObject jsonObject = JSON.parseObject(jsonStr);
                    Map<String, Object> stringObjectMap = doPost("http://10.97.240.34/fsi/api/fsiIntegratedQueryService/queryInhospInfo", jsonObject.toJSONString());
                    System.out.println(stringObjectMap.toString());
                } catch (Exception e) {

                }finally {
                    latch.countDown();
                }
            });
        }
        latch.await();
        executor.shutdown();
        System.out.println("end" + LocalTime.now());


    }
}